package controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import model.Image;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import repository.ImageRepository;
import repository.UserRepository;

@Controller
public class FileUploadController {

    @Autowired
    private ImageRepository imageRepository;

    /*@RequestMapping(value="/api/user/uploadImage", method=RequestMethod.GET)
    public @ResponseBody String provideUploadInfo() {
        return "You can upload a file by posting to this same URL.";
    }*/

    private static final String UPLOAD_FOLDER = "src/main/webapp/upload/";

    @RequestMapping(value="/api/user/uploadImage", headers = "content-type=multipart/*", method=RequestMethod.POST)
    @ResponseBody
    public Image handleFileUpload(@RequestParam("flowFilename") String name,
                                                 @RequestBody MultipartFile file){

        Image image = new Image();
        image.setExtension(FilenameUtils.getExtension(name));

        image = imageRepository.save(image);

        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(UPLOAD_FOLDER + image.getId() + "." +
                                image.getExtension())));
                stream.write(bytes);
                stream.close();
                return image;
            } catch (Exception e) {
                return null;
            }
        } else {
            return null;
        }
    }
}